<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    String adminaccount = request.getParameter("adminaccount")==null?"":request.getParameter("adminaccount");
    String adminname = request.getParameter("adminname")==null?"":request.getParameter("adminname");
    String totalPage = request.getParameter("totalPage");
    String currentPage = request.getParameter("currentPage");
    
    Integer sessionAdminStatus = (Integer) session.getAttribute("adminstatus");
    if (sessionAdminStatus == null) sessionAdminStatus = 2; // 默认超级管理员
    
%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <base href="<%= basePath %>"/>
    <title>管理员用户管理</title>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <!-- Element Plus 样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css" />
    <!-- Vue3（Element Plus 依赖） -->
    <script src="https://unpkg.com/vue@3"></script>
    <!-- Element Plus JS -->
    <script src="https://unpkg.com/element-plus"></script>
    <style>
        body {
            background: #f5f6fa;
            font-family: 'Segoe UI', 'Arial', sans-serif;
            margin: 0;
            padding: 0;
        }
        .container {
            max-width: 1200px;
            margin: 32px auto;
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 24px rgba(0,0,0,0.06);
            padding: 32px 40px;
        }
        h2 {
            color: #222;
            margin-bottom: 24px;
        }
        .search-form {
            display: flex;
            flex-wrap: wrap;
            gap: 18px;
            align-items: center;
            margin-bottom: 28px;
        }
        .search-form label {
            font-size: 1rem;
            color: #555;
            margin-right: 6px;
        }
        .search-form input[type="text"] {
            padding: 8px 12px;
            border: 1px solid #dcdde1;
            border-radius: 6px;
            font-size: 1rem;
            background: #f9f9f9;
        }
        .search-form input[type="submit"] {
            padding: 8px 28px;
            background: #4f8cff;
            color: #fff;
            border: none;
            border-radius: 6px;
            font-size: 1rem;
            cursor: pointer;
            transition: background 0.2s;
        }
        .search-form input[type="submit"]:hover {
            background: #357ae8;
        }
        .add-btn {
            padding: 8px 20px;
            background: #28a745;
            color: #fff;
            border: none;
            border-radius: 6px;
            font-size: 1rem;
            cursor: pointer;
            transition: background 0.2s;
            margin-left: auto;
        }
        .add-btn:hover {
            background: #218838;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 12px;
        }
        th, td {
            padding: 12px 8px;
            border-bottom: 1px solid #e0e0e0;
            text-align: center;
        }
        th {
            background: #f0f4ff;
            color: #333;
            font-weight: 600;
        }
        tr:hover {
            background: #f5faff;
        }
        .action-btn {
            padding: 4px 12px;
            border: none;
            border-radius: 4px;
            font-size: 0.9rem;
            cursor: pointer;
            margin: 0 2px;
            transition: background 0.2s;
        }
        .edit-btn {
            background: #ffc107;
            color: #fff;
        }
        .edit-btn:hover {
            background: #e0a800;
        }
        .delete-btn {
            background: #dc3545;
            color: #fff;
        }
        .delete-btn:hover {
            background: #c82333;
        }
        .status-active {
            color: #28a745;
            font-weight: bold;
        }
        .status-inactive {
            color: #dc3545;
            font-weight: bold;
        }
        /* 弹窗样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        .modal-content {
            background-color: #fff;
            margin: 5% auto;
            padding: 32px;
            border-radius: 12px;
            width: 500px;
            box-shadow: 0 4px 24px rgba(0,0,0,0.15);
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
        }
        .modal-title {
            font-size: 1.5rem;
            color: #222;
            margin: 0;
        }
        .close {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        .close:hover {
            color: #000;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-size: 1rem;
        }
        .form-group input, .form-group select {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #dcdde1;
            border-radius: 6px;
            font-size: 1rem;
            background: #f9f9f9;
        }
        .form-group input:focus, .form-group select:focus {
            border: 1.5px solid #4f8cff;
            outline: none;
        }
        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 12px;
            margin-top: 24px;
        }
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            font-size: 1rem;
            cursor: pointer;
            transition: background 0.2s;
        }
        .btn-primary {
            background: #4f8cff;
            color: #fff;
        }
        .btn-primary:hover {
            background: #357ae8;
        }
        .btn-secondary {
            background: #6c757d;
            color: #fff;
        }
        .btn-secondary:hover {
            background: #5a6268;
        }
        /* 分页美化 */
        .Page {
            margin-top: 20px;
            text-align: center;
        }
        .Page a, .Page strong {
            display: inline-block;
            margin: 0 4px;
            padding: 6px 16px;
            border-radius: 6px;
            font-size: 1rem;
            text-decoration: none;
            color: #4f8cff;
            background: #f0f4ff;
            border: 1px solid #e0e7ff;
            transition: background 0.2s, color 0.2s, border 0.2s;
        }
        .Page a:hover {
            background: #4f8cff;
            color: #fff;
            border: 1px solid #4f8cff;
        }
        .Page strong {
            background: #4f8cff;
            color: #fff;
            border: 1px solid #4f8cff;
            font-weight: bold;
        }
        .input-tip {
            color: #dc3545;
            font-size: 0.95rem;
            margin-left: 8px;
            vertical-align: middle;
        }
        .input-tip.success {
            color: #28a745;
        }
    </style>
</head>
<body>
<div class="container">
    <h2>管理员用户管理</h2>
    
    <!-- 搜索表单 -->
    <form class="search-form" method="get" action="AdminServlet">
        <label for="adminaccount">管理员账号：</label>
        <input type="text" id="adminaccount" name="adminaccount" placeholder="请输入管理员账号" value="<%= adminaccount %>">
        <label for="adminname">管理员姓名：</label>
        <input type="text" id="adminname" name="adminname" placeholder="请输入管理员姓名" value="<%= adminname %>">
        <input type="submit" value="搜索" >
        <% if (sessionAdminStatus == 2) { %>
            <button type="button" class="add-btn" onclick="openAddModal()">新增管理员</button>
        <% } %>
    </form>
    
    <!-- 管理员列表表格 -->
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>管理员账号</th>
                <th>管理员姓名</th>
                <!-- <th>状态</th> -->
                <th>权限等级</th>
                <th>创建时间</th>
                <th>更新时间</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <c:forEach items="${admins}" var="admin">
                <tr>
                    <td>${admin.id}</td>
                    <td>${admin.adminaccount}</td>
                    <td>${admin.adminname}</td>
                    <!-- <td><span class="status-active"><c:if test="${admin.isdeleted == 0}">启用</c:if><c:if test="${admin.isdeleted == 1}">禁用</c:if></span></td> -->
                    <td>${admin.adminstatus}</td>
                    <td>${admin.createtime}</td>
                    <td>${admin.updatetime}</td>
                    <td>
                        <% if (sessionAdminStatus == 2) { %>
                            <button class="action-btn edit-btn"
                                data-id="${admin.id}"
                                data-account="${admin.adminaccount}"
                                data-password="${admin.adminpassword}"
                                data-name="${admin.adminname}"
                                data-status="${admin.adminstatus}"
                                onclick="openEditModal(this)">编辑</button>
                            <button class="action-btn delete-btn" onclick="deleteAdmin(${admin.id})">删除</button>
                        <% } %>
                    </td>
                </tr>
            </c:forEach>
        </tbody>
    </table>
    <!-- 分页 -->
    <div style="margin-top: 20px; text-align:center;" class="Page">
        <a href="AdminServlet?&currentPage=${currentPage-1>0?currentPage-1:1}&adminaccount=${adminaccount}&adminname=${adminname}">上一页</a>
        <c:if test="${totalPage>=1}">
            <c:forEach begin="1" end="${totalPage}" var="i">
                <c:choose>
                    <c:when test="${i == currentPage}">
                        <strong>${i}</strong>
                    </c:when>
                    <c:otherwise>
                        <a href="AdminServlet?method=search&currentPage=${i}&adminaccount=${adminaccount}&adminname=${adminname}">${i}</a>
                    </c:otherwise>
                </c:choose>
            </c:forEach>
        </c:if>
        <a href="AdminServlet?&currentPage=${currentPage+1<=totalPage?currentPage+1:totalPage}&adminaccount=${adminaccount}&adminname=${adminname}">下一页</a>
    </div>
</div>

<!-- 新增/编辑弹窗 -->
<div id="adminModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title" id="modalTitle">新增管理员</h3>
            <span class="close" onclick="closeModal()">&times;</span>
        </div>
        <form id="adminForm">
            <input type="hidden" id="adminId" name="id">
            <input type="hidden" id="textContext" name="textContext">
            <div class="form-group">
                <label for="modalAdminaccount">管理员账号：</label>
                <input type="text" id="modalAdminaccount" name="adminaccount" placeholder="请输入管理员账号" required onblur="validateAccountSync();checkAccountUnique();">
                <span class="input-tip" id="tipAccount"></span>
            </div>
            <div class="form-group">
                <label for="modalAdminpassword">管理员密码：</label>
                <input type="password" id="modalAdminpassword" name="adminpassword" placeholder="请输入密码" required onblur="validatePassword()">
                <span class="input-tip" id="tipPassword"></span>
            </div>
            <div class="form-group">
                <label for="modalAdminname">管理员姓名：</label>
                <input type="text" id="modalAdminname" name="adminname" placeholder="请输入管理员姓名" required onblur="validateName()">
                <span class="input-tip" id="tipName"></span>
            </div>
            <div class="form-group" id="adminLevelGroup" style="<%= sessionAdminStatus == 2 ? "" : "display:none;" %>">
                <label for="modalAdminstatus">权限等级：</label>
                <select id="modalAdminstatus" name="adminstatus">
                    <option value="1">普通管理员</option>
                    <option value="2">超级管理员</option>
                </select>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                <button type="submit" class="btn btn-primary" onclick="submitForm()">保存</button>
            </div>
        </form>
    </div>
</div>

<script>
// 打开新增弹窗
function openAddModal() {
    document.getElementById('adminModal').style.display = 'block';
    document.getElementById('modalTitle').textContent = '新增管理员';
    document.getElementById('adminForm').reset();
    document.getElementById('tipAccount').textContent = "";
    document.getElementById('tipPassword').textContent = "";
    document.getElementById('tipName').textContent = "";
}

// 打开编辑弹窗
function openEditModal(btn) {
    document.getElementById('adminModal').style.display = 'block';
    document.getElementById('modalTitle').textContent = '编辑管理员';
    document.getElementById('adminId').value = btn.getAttribute('data-id');
    document.getElementById('modalAdminaccount').value = btn.getAttribute('data-account');
    document.getElementById('modalAdminpassword').value = btn.getAttribute('data-password');
    document.getElementById('modalAdminname').value = btn.getAttribute('data-name');
    document.getElementById('modalAdminstatus').value = btn.getAttribute('data-status');
    document.getElementById('tipAccount').textContent = "";
    document.getElementById('tipPassword').textContent = "";
    document.getElementById('tipName').textContent = "";
}

// 关闭弹窗
function closeModal() {
    document.getElementById('adminModal').style.display = 'none';
}

// 删除管理员
function deleteAdmin(id) {
    ElementPlus.ElMessageBox.confirm(
        '确定要删除这个管理员吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        $.ajax({
            type: "get",
            url: "AdminServlet?textContext=删除&id=" + id,
            dataType: "json",
            success: function (data) {
                if (data.code == 200) {
                    ElementPlus.ElMessage.success('删除成功！');
                    location.reload();
                } else {
                    ElementPlus.ElMessage.error('删除失败！');
                }
            },
            error: function () {
                ElementPlus.ElMessage.error('删除失败！!!!!');
            }
        });
    }).catch(() => {
        // 用户点击了取消，不做任何事
    });
}

// 表单提交
function submitForm(e) {
    if (e) e.preventDefault();
    var valid = validateAccountSync() & validatePassword() & validateName();
    if (!valid) return false;
    // 这里可以再判断 tipAccount 是否为“账号已存在”，如是则 return false
    if (document.getElementById('tipAccount').textContent === "账号已存在") {
        ElementPlus.ElMessage.warning('账号已存在，请更换账号');
        return false;
    }
    var textContext = document.getElementById('modalTitle').textContent;
    console.log("textContext:"+textContext);
    var id = document.getElementById('adminId').value;
    var adminaccount = document.getElementById('modalAdminaccount').value;
    var adminpassword = document.getElementById('modalAdminpassword').value;
    var adminname = document.getElementById('modalAdminname').value;
    var adminstatus = document.getElementById('modalAdminstatus').value;
    $.ajax({
        type: "post",
        url: "AdminServlet",
        data: {
            textContext: textContext,
            id: id,
            adminaccount: adminaccount,
            adminpassword: adminpassword,
            adminname: adminname,
            adminstatus: adminstatus
        },
        dataType: "json",
        success: function (data) {
            if (data.code == 200) {
                ElementPlus.ElMessage.success('保存成功！');
                document.getElementById('adminModal').style.display = 'none';
                location.reload();
            } else {
                ElementPlus.ElMessage.error('保存失败！');
            }
        },
        error: function (data) {
            ElementPlus.ElMessage.error(data);
        }
    });
    
    closeModal();
}

function validateAccountSync() {
    var val = document.getElementById('modalAdminaccount').value.trim();
    var tip = document.getElementById('tipAccount');
    if (!val) {
        tip.textContent = "账号不能为空";
        tip.className = "input-tip";
        return false;
    }
    if(val.length > 12 || val.length < 6){
        tip.textContent = "账号长度不能小于6位或大于12位";
        tip.className = "input-tip";
        return false;
    }
    tip.textContent = "";
    return true;
}

function checkAccountUnique() {
    var val = document.getElementById('modalAdminaccount').value.trim();
    var id = document.getElementById('adminId').value;
    var tip = document.getElementById('tipAccount');
    if (!val) return;
    $.ajax({
        type: "get",
        url: "AdminServlet?textContext=checkAdminaccount&adminaccount=" + val +"&id=" + id,
        dataType: "json",
        success: function (data) {
            if (data.code == 200) {
                tip.textContent = "√";
                tip.className = "input-tip success";
            } else {
                tip.textContent = "账号已存在";
                tip.className = "input-tip";
            }
        },
        error: function () {  
            tip.textContent = "账号校验失败";
            tip.className = "input-tip";
        }
    });
}

function validatePassword() {
    var val = document.getElementById('modalAdminpassword').value.trim();
    var tip = document.getElementById('tipPassword');
    if (!val) {
        tip.textContent = "密码不能为空";
        tip.className = "input-tip";
        return false;
    }
    if (val.length < 6 && val.length > 12) {
        tip.textContent = "密码长度不能小于6位或大于12位";
        tip.className = "input-tip";
        return false;
    }
    tip.textContent = "√";
    tip.className = "input-tip success";
    return true;
}

function validateName() {
    var val = document.getElementById('modalAdminname').value.trim();
    var tip = document.getElementById('tipName');
    if (!val) {
        tip.textContent = "姓名不能为空";
        tip.className = "input-tip";
        return false;
    }
    tip.textContent = "√";
    tip.className = "input-tip success";
    return true;
}


// 点击弹窗外部关闭
window.onclick = function(event) {
    var modal = document.getElementById('adminModal');
    if (event.target == modal) {
        closeModal();
    }
}
</script>
</body>
</html>